<template>
  <div class="message-container">
    <el-row :gutter="20">
      <!-- 左侧：消息列表 -->
      <el-col :span="16">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>消息中心</span>
              <div class="header-actions">
                <el-badge :value="unreadCount" :max="99" class="badge">
                  <el-button size="small" @click="handleMarkAllRead">
                    <el-icon><Check /></el-icon>
                    全部已读
                  </el-button>
                </el-badge>
                <el-button size="small" @click="fetchData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>

          <!-- 筛选 -->
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部消息" name="all">
              <template #label>
                <span>全部消息</span>
                <el-badge :value="totalCount" :max="99" class="tab-badge" />
              </template>
            </el-tab-pane>
            <el-tab-pane label="审批通知" name="approval">
              <template #label>
                <span>审批通知</span>
                <el-badge :value="approvalCount" :max="99" class="tab-badge" />
              </template>
            </el-tab-pane>
            <el-tab-pane label="系统公告" name="notice">
              <template #label>
                <span>系统公告</span>
                <el-badge :value="noticeCount" :max="99" class="tab-badge" />
              </template>
            </el-tab-pane>
            <el-tab-pane label="成绩通知" name="score">
              <template #label>
                <span>成绩通知</span>
                <el-badge :value="scoreCount" :max="99" class="tab-badge" />
              </template>
            </el-tab-pane>
          </el-tabs>

          <!-- 消息列表 -->
          <div class="message-list" v-loading="loading">
            <div 
              v-for="item in messageList" 
              :key="item.id" 
              class="message-item"
              :class="{ 'unread': !item.isRead, 'active': currentMessage?.id === item.id }"
              @click="handleSelect(item)"
            >
              <div class="message-icon" :class="`type-${item.type}`">
                <el-icon v-if="item.type === 'approval'"><DocumentChecked /></el-icon>
                <el-icon v-else-if="item.type === 'notice'"><Bell /></el-icon>
                <el-icon v-else-if="item.type === 'score'"><Trophy /></el-icon>
                <el-icon v-else><Message /></el-icon>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <span class="message-title">{{ item.title }}</span>
                  <span class="message-time">{{ formatTime(item.createTime) }}</span>
                </div>
                <div class="message-preview">{{ item.content }}</div>
                <div class="message-footer">
                  <el-tag size="small" :type="getTypeTag(item.type)">
                    {{ getTypeText(item.type) }}
                  </el-tag>
                </div>
              </div>
              <div class="unread-dot" v-if="!item.isRead"></div>
            </div>

            <el-empty v-if="messageList.length === 0" description="暂无消息" />
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="messageList.length > 0">
            <el-pagination
              v-model:current-page="queryForm.current"
              v-model:page-size="queryForm.size"
              :page-sizes="[10, 20, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next"
              @size-change="fetchData"
              @current-change="fetchData"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：消息详情 -->
      <el-col :span="8">
        <el-card shadow="never" class="detail-card">
          <template #header>
            <div class="card-header">
              <span>消息详情</span>
              <el-button 
                size="small" 
                type="danger" 
                link 
                @click="handleDelete" 
                v-if="currentMessage"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>

          <div class="message-detail" v-if="currentMessage">
            <div class="detail-header">
              <h3>{{ currentMessage.title }}</h3>
              <el-tag :type="getTypeTag(currentMessage.type)">
                {{ getTypeText(currentMessage.type) }}
              </el-tag>
            </div>
            <div class="detail-meta">
              <span><el-icon><Clock /></el-icon> {{ currentMessage.createTime }}</span>
            </div>
            <el-divider />
            <div class="detail-content" v-html="currentMessage.content"></div>
            
            <!-- 操作按钮 -->
            <div class="detail-actions" v-if="currentMessage.type === 'approval'">
              <el-button type="primary" @click="handleViewApproval">
                查看审批详情
              </el-button>
            </div>
          </div>

          <el-empty v-else description="请选择一条消息查看详情" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Check, 
  Refresh, 
  Delete, 
  Clock, 
  DocumentChecked, 
  Bell, 
  Trophy, 
  Message 
} from '@element-plus/icons-vue'
import { getMessagePage, markMessageRead, markAllRead, deleteMessage, getMessageStatistics } from '@/api/message'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()

interface MessageItem {
  id: number
  type: string
  title: string
  content: string
  isRead: boolean
  createTime: string
  relatedId?: number  // 关联ID（如审批ID）
}

// 用户角色判断
const isStudent = computed(() => userStore.userInfo?.roleCode === 'student')
const isAdminOrTeacher = computed(() => 
  userStore.userInfo?.roleCode === 'admin' || userStore.userInfo?.roleCode === 'teacher'
)

// Tab
const activeTab = ref('all')

// 查询表单
const queryForm = reactive({
  current: 1,
  size: 10,
  type: ''
})

// 消息列表
const messageList = ref<MessageItem[]>([])
const total = ref(0)
const loading = ref(false)
const currentMessage = ref<MessageItem | null>(null)

// 统计数据
const unreadCount = ref(0)
const totalCount = ref(0)
const approvalCount = ref(0)
const noticeCount = ref(0)
const scoreCount = ref(0)

// 类型文本
const getTypeText = (type: string) => {
  const map: Record<string, string> = {
    'approval': '审批通知',
    'notice': '系统公告',
    'score': '成绩通知',
    'other': '其他'
  }
  return map[type] || '未知'
}

// 类型标签
const getTypeTag = (type: string) => {
  const map: Record<string, string> = {
    'approval': 'warning',
    'notice': '',
    'score': 'success',
    'other': 'info'
  }
  return map[type] || ''
}

// 格式化时间
const formatTime = (time: string) => {
  const now = new Date()
  const msgTime = new Date(time)
  const diff = now.getTime() - msgTime.getTime()
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return time
}

// 获取消息列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      current: queryForm.current,
      size: queryForm.size,
      type: activeTab.value === 'all' ? '' : activeTab.value
    }
    const data = await getMessagePage(params)
    messageList.value = data.records || []
    total.value = data.total || 0
  } catch (error) {
    console.error('加载消息失败', error)
    ElMessage.error('加载消息失败')
    messageList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
  
  // 同时获取统计数据
  fetchStatistics()
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const stats = await getMessageStatistics()
    unreadCount.value = stats.unreadCount || 0
    totalCount.value = stats.totalCount || 0
    approvalCount.value = stats.approvalCount || 0
    noticeCount.value = stats.noticeCount || 0
    scoreCount.value = stats.scoreCount || 0
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// Tab切换
const handleTabChange = () => {
  queryForm.current = 1
  currentMessage.value = null
  fetchData()
}

// 选择消息
const handleSelect = async (item: MessageItem) => {
  currentMessage.value = item
  
  // 标记为已读
  if (!item.isRead) {
    item.isRead = true
    
    // 调用API标记已读
    try {
      await markMessageRead(item.id)
      // 重新获取统计数据
      fetchStatistics()
    } catch (error) {
      console.error('标记已读失败', error)
    }
  }
}

// 全部已读
const handleMarkAllRead = async () => {
  try {
    await ElMessageBox.confirm('确定将所有消息标记为已读吗？', '提示', {
      type: 'warning'
    })
    
    // 调用API全部标记已读
    await markAllRead()
    
    messageList.value.forEach(item => item.isRead = true)
    
    // 重新获取统计数据
    fetchStatistics()
    
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败', error)
    }
  }
}

// 删除消息
const handleDelete = async () => {
  if (!currentMessage.value) return
  
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      type: 'warning'
    })
    
    const messageToDelete = currentMessage.value
    
    // 调用API删除
    await deleteMessage(currentMessage.value.id)
    
    // 从列表中移除
    const index = messageList.value.findIndex(item => item.id === messageToDelete.id)
    if (index > -1) {
      messageList.value.splice(index, 1)
      total.value--
    }
    
    // 重新获取统计数据
    fetchStatistics()
    
    currentMessage.value = null
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

// 查看审批详情
const handleViewApproval = () => {
  if (!currentMessage.value) return
  
  // 检查是否有关联的审批ID
  if (!currentMessage.value.relatedId) {
    ElMessage.warning('该消息没有关联的审批记录')
    return
  }
  
  // 根据用户角色跳转到不同的页面
  if (isStudent.value) {
    // 学生跳转到"我的申请"页面
    router.push({
      path: '/student/apply',
      query: { approvalId: currentMessage.value.relatedId }
    })
    ElMessage.success('正在跳转到我的申请...')
  } else if (isAdminOrTeacher.value) {
    // 管理员/教师跳转到"审批中心"页面
    router.push({
      path: '/approval',
      query: { approvalId: currentMessage.value.relatedId }
    })
    ElMessage.success('正在跳转到审批中心...')
  } else {
    ElMessage.warning('无权限查看审批详情')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.message-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      gap: 10px;

      .badge {
        :deep(.el-badge__content) {
          font-weight: bold;
        }
      }
    }
  }

  .tab-badge {
    margin-left: 5px;
    :deep(.el-badge__content) {
      transform: translateY(-8px);
    }
  }

  .message-list {
    min-height: 400px;

    .message-item {
      display: flex;
      gap: 15px;
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      position: relative;
      transition: all 0.3s;

      &:hover {
        background: #f5f7fa;
      }

      &.active {
        background: #ecf5ff;
        border-left: 3px solid #409EFF;
      }

      &.unread {
        background: #fef0f0;
        
        .message-title {
          font-weight: bold;
        }
      }

      .message-icon {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        flex-shrink: 0;

        &.type-approval {
          background: #fdf6ec;
          color: #e6a23c;
        }

        &.type-notice {
          background: #f0f9ff;
          color: #409EFF;
        }

        &.type-score {
          background: #f0f9ff;
          color: #67c23a;
        }

        &.type-other {
          background: #f4f4f5;
          color: #909399;
        }
      }

      .message-content {
        flex: 1;
        overflow: hidden;

        .message-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .message-title {
            font-size: 15px;
            color: #303133;
          }

          .message-time {
            font-size: 12px;
            color: #909399;
            flex-shrink: 0;
            margin-left: 10px;
          }
        }

        .message-preview {
          font-size: 13px;
          color: #606266;
          line-height: 1.5;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          margin-bottom: 8px;
        }

        .message-footer {
          display: flex;
          align-items: center;
        }
      }

      .unread-dot {
        position: absolute;
        top: 50%;
        right: 15px;
        transform: translateY(-50%);
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #f56c6c;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .detail-card {
    height: calc(100vh - 160px);
    overflow-y: auto;

    .message-detail {
      .detail-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 10px;

        h3 {
          margin: 0;
          font-size: 18px;
          color: #303133;
          flex: 1;
        }
      }

      .detail-meta {
        font-size: 13px;
        color: #909399;
        display: flex;
        align-items: center;
        gap: 5px;
      }

      .detail-content {
        font-size: 14px;
        line-height: 1.8;
        color: #606266;
        white-space: pre-wrap;
      }

      .detail-actions {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #f0f0f0;
      }
    }
  }
}
</style>

